import {
  getInfo,
  login,
  logout
} from '@/api/user'
import router, {
  resetRouter
} from '@/router'
import {
  getToken,
  removeToken,
  setToken
} from '@/utils/auth'
import {
  Message
} from 'element-ui'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  menuList: [],
  staffCode: '', //员工code  PINGTAI admin 权限
  companyId: '', //公司id
  companyName: '',
  branchId: '', //门店id 
  branchName: '',
  staffName: '', //员工名称
  staffPhone: '', //员工电话
  isRetrofitting: '', //是否开启选装 1开启 2关闭  控制 选装字段、选装包售价
  isDescribe: '', //DCC描述1开启 2关闭
  roleName: '', //角色名称

}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  STAFF_NAME: (state, staffName) => {
    state.staffName = staffName
  },
  STAFF_PHONE: (state, staffPhone) => {
    state.staffPhone = staffPhone
  },
  SET_STAFFCODE: (state, staffCode) => {
    state.staffCode = staffCode
  },
  COMPANY_NAME: (state, companyName) => {
    state.companyName = companyName
  },
  COMPANY_ID: (state, companyId) => {
    state.companyId = companyId
  },
  BRANCH_ID: (state, branchId) => {
    state.branchId = branchId
  },
  BRANCH_NAME: (state, branchName) => {
    state.branchName = branchName
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    if (roles && Object.prototype.toString.call(roles) === '[object Array]') {
      state.roles = roles
    } else {
      state.roles = [];
    }
  },
  SET_MENU_LIST: (state, menuList) => {
    if (menuList && Object.prototype.toString.call(menuList) === '[object Array]') {
      state.menuList = menuList;
    } else {
      state.menuList = [];
    }
  },
  IS_RETRORFITTING: (state, isRetrofit) => {
    state.isRetrofitting = isRetrofit
  },
  IS_DESCRIBE: (state, isDescribe) => {
    state.isDescribe = isDescribe
  },
  ROLENAME: (state, roleName) => {
    state.roleName = roleName.replace(/,/g, "/")
  },

}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      username,
      password,
      code,
      codeId
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        userName: username.trim(),
        passWord: password,
        code,
        codeId
      }).then(response => {
        commit('SET_TOKEN', response.data.token)
        setToken(response.data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response
        if (!data) {
          reject('验证失败，请重新登录')
        }
        if (data.menus && data.menus.length > 0) {
          const {
            roles,
            menus,
            staffCode,
            headImg,
            userName,
            staffName,
            staffPhone,
            branchId,
            branchName,
            companyId,
            companyName,
            isRetrofit,
            isDescribe
          } = data
          const roleNames = [];
          if (data.roles) {
            data.roles.forEach(i => {
              roleNames.push(i.name)
            });
          }
          const roleName = roleNames.toString()
          commit('SET_ROLES', roles)
          commit('SET_MENU_LIST', menus)
          commit('BRANCH_ID', branchId)
          commit('BRANCH_NAME', branchName)
          commit('COMPANY_ID', companyId)
          commit('COMPANY_NAME', companyName)
          commit('SET_NAME', userName)
          commit('STAFF_NAME', staffName)
          commit('STAFF_PHONE', staffPhone)
          commit('SET_STAFFCODE', staffCode)
          commit('SET_AVATAR', headImg)
          commit('IS_RETRORFITTING', isRetrofit)
          commit('IS_DESCRIBE', isDescribe)
          commit('ROLENAME', roleName)
          resolve(data)
        } else {
          Message.error('请联系管理员设置菜单权限')
          dispatch('tagsView/delAllViews', null, {
            root: true
          })
          resolve()
          // return false
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state,
    dispatch
  }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_NAME', '')
        commit('SET_STAFFCODE', '')
        commit('BRANCH_ID', '')
        commit('BRANCH_NAME', '')
        commit('COMPANY_ID', '')
        commit('COMPANY_NAME', '')
        commit('STAFF_NAME', '')
        commit('STAFF_PHONE', '')
        commit('SET_MENU_LIST', [])
        commit('SET_AVATAR', '')
        commit('IS_RETRORFITTING', '')
        commit('IS_DESCRIBE', '')
        commit('ROLENAME', '')
        commit('SET_LANGUAGE', '')
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, {
          root: true
        })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({
    commit,
    dispatch
  }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const {
      roles
    } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, {
      root: true
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
